package com.mrd.frame.onlinepay;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.mrd.frame.attachment.AttachmentService;

@Component
public class QrCreateBean {
	@Autowired
	AttachmentService attachmentService;
	@Value("${pay.weixin.systemPublishPath}")
	private String	publishPath;
	
	public String saveQr(String code_url,String nonStr) {
		String retStr = "";
		try {
			int width = 200;
			int height = 200;
			String format = "png";
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix = new MultiFormatWriter()
			        .encode(code_url, BarcodeFormat.QR_CODE, width, height, hints);
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			for(int x = 0;x < width;x++) {
				for(int y = 0;y < height;y++) {
					image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
				}
			}

			//创建储存图片二进制流的输出流
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			//创建ImageOutputStream流
			ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
			//将二进制数据写进ByteArrayOutputStream
			ImageIO.write(image, format, imageOutputStream);
			attachmentService.upload(new ByteArrayInputStream(baos.toByteArray()), nonStr+".png");
			retStr = publishPath + "/qrimages" + "/" + nonStr + ".png";// PayConfig.systemPublishPaht
			return retStr;

		} catch (WriterException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return retStr;

	}
}
